import React, { Component } from 'react';
import { Switch, InputNumber, Modal, Form, Row, Col, Space, Button, Input, Checkbox, Select, message } from "antd";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import GoBack from '@/components/TheGoBack'
import { apiGetWebMemberWalletDetail, apiFreezeMemberWalletPrice, apiGetMemberWalletFreezeRecordPage, apiUpdateMemberWalletStatus, apiGetMemberWalletWebRecordPage } from '@/request/wallet/userBalance.js'

export default class EventTracking extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef();
    this.FeatureFormRef = React.createRef();
    this.state = {
      frozenVisible: false,
      title: "",
      amount: "",
      FeatureVisible: false,
      RecordsVisible: false,
      amountTitle: '',
      memberWalletStatusArr: { N: [], C: ["C"], T: ["T"], A: ["C", "T"] },
      recordsColumns: [
        {
          title: "冻结类型",
          key: "type",
          dataIndex: "type",
          render: (text, render) => {
            let txt = ''
            switch (text) {
              case "J":
                txt = '解冻'
                break;
              case "D":
                txt = '冻结'
                break;
              default:
                break;
            }
            return txt;
          }

        },
        {
          title: "类型",
          key: "recordType",
          dataIndex: "recordType",
          render: (text, render) => {
            const arr = {
              CZSR: "充值收入", HBSR: "红包收入", HBTH: "红包退回", ZZSR: "转账收入", ZZTH: "转账退回", TXTH: "提现退回", QTSR: "其他收入", TXZC: "提现支出", HBZC: "红包支出", ZZZC: "转账支出", QTZC: "其他支出", RGCZ: "人工操作"
            }
            return arr[text]
          }

        },
        {
          title: "金额",
          key: "changePrice",
          dataIndex: "changePrice",
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "冻结备注",
          key: "remark",
          dataIndex: "remark",
        },
        {
          title: "操作时间",
          key: "createTime",
          dataIndex: "createTime",
        },
      ],

      columns1: [
        {
          title: "会员ID",
          key: "memberId",
          dataIndex: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        // {
        //   title: "实名姓名",
        //   key: "name",
        //   dataIndex: 'name'
        // },
        {
          title: "会员手机号",
          key: "memberMobile",
          dataIndex: 'memberMobile',
          render: (text) => {
            var reg = /^(\d{3})\d{4}(\d{4})$/;
            var memberMobile = text.toString().replace(reg, '$1****$2');
            return memberMobile;
          }
        },
        {
          title: "会员状态",
          key: "memberStatus",
          dataIndex: 'memberStatus',
          render: (text, _) => {
            return { "Y": "正常", "N": "冻结" }[text]
          }
        },
        {
          title: "功能禁用",
          key: "memberWalletStatusContent",
          dataIndex: 'memberWalletStatusContent',
          // render: (text, render) => {
          //   let txt = ''
          //   switch (text) {
          //     case "N":
          //       txt = '正常'
          //       break;
          //     case "C":
          //       txt = '充值禁用'
          //       break;
          //     case "T":
          //       txt = '提现禁用'
          //       break;
          //     case "A":
          //       txt = '充值禁用、提现禁用'
          //       break;
          //     default:
          //       break;
          //   }
          //   return txt;
          // }
        },

      ],
      info: "",
      columns2: [
        {
          title: "钱包余额",
          key: "memberWalletPrice",
          dataIndex: "memberWalletPrice",
          render: text => text && <React.$price price={text} />,

        },
        {
          title: "支出统计",
          dataIndex: "expendPrice",
          key: "expendPrice",
          render: text => text && <React.$price price={text} />,

        },
        {
          title: "收入统计",
          key: "incomePrice",
          dataIndex: 'incomePrice',
          render: text => text && <React.$price price={text} />,

        },
        {
          title: "不可用余额",
          key: "walletFrozenPrice",
          dataIndex: 'walletFrozenPrice',
          render: (text, render) => {
            return (
              <div>
                <TheButton onClick={() => this.goAccountDetail(render.memberId)}><React.$price price={text} /></TheButton>
              </div>
            );
          },
        },
        {
          title: "可用余额",
          key: "walletUsablePrice",
          dataIndex: 'walletUsablePrice',
          render: text => text && <React.$price price={text} />,
        },
        {
          title: "查看详情",
          key: "activityStatus",
          dataIndex: 'activityStatus',
          render: (text, render) => {
            return (
              <div>
                <TheButton onClick={() => this.showRecordsVisible(render.memberId)}>查看资产明细</TheButton>
              </div>
            );
          },
        },
      ],
      dataSource: [],
      type: "",
      dataSourceRecords: [],
      pageData1: {
        pageNo: 1,
        pageSize: 10,
      },
      walletFrozenPrice: 0,
      pageData2: {
        pageNo: 1,
        pageSize: 10,
      },
      pageDataRecords: { pageNoRecords: 1, pageSizeRecords: 10 },
      totalRecords: 0,
      memberWalletStatus: [],
      total1: 0,
      total2: 0,

    }
  }
  componentDidMount() {
    this.getData()
  }
  goAccountDetail = async (memberId) => {
    // this.props.history.push(`/wallet/userBalance/detail/${id}`);
    const { pageNoRecords, pageSizeRecords } = this.state.pageDataRecords
    console.log(pageNoRecords, pageSizeRecords);
    let res = await apiGetMemberWalletFreezeRecordPage({
      memberId: memberId,
      pageNo: pageNoRecords,
      pageSize: pageSizeRecords,
    })
    if (res.code === 0 && res.data) {
      this.setState({
        pageDataRecords: {
          pageNoRecords: res.pageNo,
          pageSizeRecords: res.pageSize
        },
        dataSourceRecords: res.data,
        totalRecords: res.totalCount,
        RecordsVisible: true
      })
    }
  }

  // 获取表格数据
  getData = async () => {
    const { id } = this.props.match.params
    let res = await apiGetWebMemberWalletDetail(id)
    if (res.code === 0 && res.data) {
      console.log(this.state.memberWalletStatusArr[res.data.memberWalletStatus]);
      this.setState({
        dataSource: [res.data],
        walletFrozenPrice: res.data.walletFrozenPrice,
        memberWalletStatus: this.state.memberWalletStatusArr[res.data.memberWalletStatus],
      },)
    }
  };
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageDataRecords: {
        pageNoRecords: pageNo,
        pageSizeRecords: pageSize,
      }
    },()=>{
      this.goAccountDetail(this.state.dataSource[0].memberId)
    })
  }
  // 取消
  handleCancel = () => {
    this.FormRef.current.resetFields()
    this.setState({
      frozenVisible: false,
    })
  };
  handleFinish = async (values) => {
    console.log(values.changePrice, "=====", this.state.amount);
    if (values.changePrice <= 0) {
      return message.error(["解结", "冻结"][this.state.type] + '金额需大于0');
    } else if (React.$transNum(values.changePrice, 2, 2) > this.state.amount) {
      return message.error(["解结", "冻结"][this.state.type] + '金额不能大于' + this.state.amountTitle);
    }
    let res = await apiFreezeMemberWalletPrice({
      type: ["J", "D"][this.state.type],
      remark: values.remark,
      memberId: this.state.dataSource[0].memberId,
      changePrice: parseInt(React.$transNum(values.changePrice, 2, 2)),
      recordType: "RGCZ"
    }
    )
    if (res.code === 0 && res.data) {

      this.setState({
        frozenVisible: false
      }, () => {
        this.FormRef.current.resetFields()
        React.$message({ content: '修改成功', type: 'success', })
        this.getData()
      })
    }
  }
  handleFinishOnly = async (values) => {
    let memberWalletStatus;
    switch (this.state.memberWalletStatus.length) {
      case 2:
        memberWalletStatus = 'A'
        break;
      case 1:
        memberWalletStatus = this.state.memberWalletStatus[0]
        break;
      case 0:
        memberWalletStatus = 'N'
        break;
    }

    let res = await apiUpdateMemberWalletStatus({
      memberId: this.state.dataSource[0].memberId,
      memberWalletStatus,
    }
    )
    if (res.code === 0 && res.data) {
      this.setState({
        FeatureVisible: false
      }, () => {
        this.getData()
        this.FeatureFormRef.current.resetFields()
        React.$message({ content: '修改成功', type: 'success', })
      })
    }
  }
  handleFeatureCancel = () => {
    this.FeatureFormRef.current.resetFields()
    this.setState({
      FeatureVisible: false,
    })
  };
  pageChange2 = (pageNo, pageSize) => {
    this.setState({
      pageData2: {
        pageNo,
        pageSize
      }
    })
  }
  CheckboxChange = (params) => {
    this.setState({
      memberWalletStatus: params
    })
  }
  showRecordsVisible = async (memberId) => {
    this.props.history.push(`/wallet/userBalance/detail/${memberId}`);
    // const { pageNoRecords, pageSizeRecords } = this.state.pageDataRecords
    // console.log(pageNoRecords, pageSizeRecords);
    // let res = await apiGetMemberWalletWebRecordPage({
    //     memberId: memberId,
    //     pageNo: pageNoRecords,
    //     pageSize: pageSizeRecords,
    // })
    // if (res.code === 0 && res.data) {
    //     this.setState({
    //         pageDataRecords: {
    //             pageNoRecords: res.pageNo,
    //             pageSizeRecords: res.pageSize
    //         },
    //         dataSourceRecords:res.data,
    //         totalRecords: res.totalCount,
    //         RecordsVisible: true
    //     })
    // }
  }
  showModel = (title, type) => {
    const { walletUsablePrice, walletFrozenPrice, nickName, memberMobile } = this.state.dataSource[0]
    this.setState({
      type,
      info: `${nickName}(${memberMobile})`,
      amountTitle: ['冻结金额', '可用余额'][type],
      amount: [walletFrozenPrice, walletUsablePrice][type],
      title,
      frozenVisible: true
    },)
  }

  showFeature = async () => {
    this.setState({
      FeatureVisible: true
    })
  }
  render() {
    const { walletFrozenPrice, info, memberWalletStatus, recordsColumns, amountTitle, pageDataRecords: { pageNoRecords, pageSizeRecords }, pageDataRecords, totalRecords, dataSourceRecords, frozenVisible, RecordsVisible, FeatureVisible, amount, title, columns1, dataSource, columns2, dataSource2, pageData1, pageData2, total1, total2, FormRef } = this.state

    return (
      <div className="p-layout-box">
        <GoBack history={this.props.history} title="" />

        <div style={{ fontWeight: 'bold' }}>会员信息</div>
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns1}
            dataSource={dataSource}
            pageData={pageData1}
          />
        </div>
        <div style={{ fontWeight: 'bold' }}>账户信息</div>
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns2}
            dataSource={dataSource}
            pageData={pageData2}
          />
        </div>
        <div style={{ textAlign: "center", transform: "translateY(-50px)" }}>
          {walletFrozenPrice > 0 && <TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showModel('解冻金额', 0)}>解冻金额</TheButton>}
          <TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={() => this.showModel('冻结金额', 1)}>冻结金额</TheButton>
          {/*<TheButton type="primary" size="middle" style={{ marginRight: '20px' }} onClick={this.showFeature}>功能禁用</TheButton>*/}
        </div>
        <Modal title={'功能禁用'} visible={FeatureVisible} width="40%"
          onCancel={() => this.handleFeatureCancel()}
          footer={null}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FeatureFormRef}
            onFinish={(values) => this.handleFinishOnly(values)}
          >
            <Form.Item
              label="禁用功能"
            // name="memberWalletStatus"
            >
              <Checkbox.Group
                options={[{
                  label: '提现',
                  value: 'T',
                },
                {
                  label: '充值',
                  value: 'C',
                }]}
                defaultValue={memberWalletStatus}
                onChange={this.CheckboxChange}
              />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>
                <Button type="default" onClick={() => this.handleFeatureCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal >
        <Modal title={'冻结解冻记录'} visible={RecordsVisible} width="70%" footer={null}
          onCancel={() => this.setState({ RecordsVisible: false, pageDataRecords: { pageNoRecords: 1, pageSizeRecords: 10 }, })}
        >
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={recordsColumns}
            dataSource={dataSourceRecords}
            pageData={pageDataRecords}
          />
          <ThePagination
            pageNo={pageNoRecords}
            pageSize={pageSizeRecords}
            total={totalRecords}
            pageChange={this.pageChange}
          />
        </Modal >

        <Modal title={title} visible={frozenVisible} width="30%"
          onCancel={() => this.handleCancel()}
          footer={null}
        >
          <Form
            labelCol={{
              span: 6,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.handleFinish(values)}
          >
            <Form.Item
              label="会员"
            >
              {info}
            </Form.Item>
            <Form.Item
              label={title}
              name="changePrice"
              rules={[
                {
                  required: true,
                  message: '请输入' + title,
                },
              ]}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <InputNumber placeholder={'请输入' + title} />
                <div style={{ whiteSpace: 'nowrap', marginLeft: "20px" }}>{amountTitle + ': '}<React.$price price={amount} /></div>
              </div>
            </Form.Item>
            <Form.Item
              label="备注"
              name="remark"
              rules={[
                {
                  required: true,
                  message: '请输入备注',
                },
              ]}
            >
              <Input placeholder='请输入备注，200字以内' maxLength={200} />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>
                <Button type="default" onClick={() => this.handleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div >
    );
  }
}
